const CartUsers = require('../model/cartUsers.model')

const { Op, where } = require('sequelize')

class CartUsersService {
    // 新增
    async createCartUsersService({ name, nickname, email, phone }) {

        const res = await CartUsers.create({ name, nickname, email, phone })

        return res
    }

    // 删除
    async deleteCartUsersService({ userId }) {
        if (!userId) return

        const whereOpt = {}

        userId && Object.assign(whereOpt, { userId })

        const res = await CartUsers.destroy({ where: whereOpt })

        return res

    }

    // 修改
    async putCartUsersService(params) {
        const { userId } = params
        if (!userId) return

        const whereOpt = {}
        userId && Object.assign(whereOpt, { userId })

        const res = await CartUsers.update(params, { where: whereOpt })

        return res
    }

    // 查询
    async getCartUsersService({ name, nickname, email, phone, pageCurrent = 1, pageSize = 10 }) {
        const whereOpt = {}
        // 短路运算
        name && Object.assign(whereOpt, { name: { [Op.like]: `%${name}%` } })
        nickname && Object.assign(whereOpt, { nickname: { [Op.like]: `%${nickname}%` } })  // 不为空则添加到whereOpt中,模糊查询
        email && Object.assign(whereOpt, { email: { [Op.like]: `%${email}%` } })  // 不为空则添加到whereOpt中,模糊查询
        phone && Object.assign(whereOpt, { phone: { [Op.like]: `%${phone}%` } })  // 不为空则添加到whereOpt中,模糊查询

        const { count, rows } = await CartUsers.findAndCountAll({
            // attributes: ['id', 'username', 'password', 'is_admin'],
            // orderBy:[
            //     ['updatedAt','DESC'],
            //     // ['updatdeAt','ASC'],
            //     ['createdAt', 'DESC'],
            //     // ['createdAt', 'ASC'],
            // ],
            order: [['updatedAt','DESC'],['createdAt', 'DESC']],
            where: whereOpt,
            limit: pageSize,
            offset: (pageCurrent - 1) * pageSize
        })

        // 可以看一下上面res 的结构
        return { data: rows, total: count, pageSize, pageCurrent }

    }
}

// 导出后 在控制器 controller中使用
module.exports = new CartUsersService()